package uk.co.richardwkirk.parkrun.android;

import uk.co.richardwkirk.parkrun.android.dataload.cache.AthleteCache;
import uk.co.richardwkirk.parkrun.android.events.displays.EventDisplay;
import uk.co.richardwkirk.parkrun.data.athletes.AthleteSummary;
import uk.co.richardwkirk.parkrun.geo.Region;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

public class AthleteDisplay extends SharedDataReadyActivity {

	AthleteSummary athlete = null;

	long athleteId = ActiveSelections.NO_SELECTED_ATHLETE_ID;
	long compareAthleteId = ActiveSelections.NO_SELECTED_ATHLETE_ID;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set the athlete display as the activity layout
		setContentView(R.layout.athlete_display);

		// Get the athlete number from the current selections
		athleteId = ActiveSelections.getSingleton().getAthleteId();
		
		// Have we already loaded the athlete?
		doAthleteLoad(athleteId, false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.athlete_stats, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.athlete_stats_menu_runcount:
		case R.id.athlete_stats_menu_club:
		case R.id.athlete_stats_menu_pindex:
		case R.id.athlete_stats_menu_dataload:
			showStatusMessage(item.getItemId());
			break;
		case R.id.athlete_stats_menu_reload:
			doAthleteLoad(athleteId, true);
			break;
		case R.id.athlete_stats_menu_compare:
			compareAthletes();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	
	private void compareAthletes() {
		// Start the athlete selection panel
		Intent intent = new Intent(this, AthleteChoice.class);
		intent.putExtra(IntentExtras.EXTRA_ATHLETE_CHOICE_TITLE, "Select athlete to compare against...");
		intent.putExtra(IntentExtras.EXTRA_ATHLETE_CHOICE_MODE, IntentExtras.ATHLETE_CHOICE_MODE_SELECT);
		intent.putExtra(IntentExtras.EXTRA_ATHLETE_CHOICE_TYPE, IntentExtras.ATHLETE_CHOICE_TYPE_COMPARE_ATHLETE);
		startActivityForResult(intent, IntentExtras.REQUEST_ATHLETE_CHOICE_COMPARE_ATHLETE_EVENTS);	
	}
	
	/** 
	 * Handle activity results for requests we have invoked.
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("PARKRUN", "Activity result returned to athlete display:" + requestCode);
		switch (requestCode) {
			case IntentExtras.REQUEST_ATHLETE_CHOICE_COMPARE_ATHLETE_EVENTS:
				// Handle the selected athlete
				compareAthleteId = data.getLongExtra(IntentExtras.EXTRA_ATHLETE_CHOICE_SELECTED_ATHLETE, -1);
				Log.i("PARKRUN", "Athlete selected to compare: " + compareAthleteId);
				loadEventData(IntentExtras.REQUEST_EVENT_DATA_COMPARE_ATHLETE_EVENTS);
				break;
			default:
				super.onActivityResult(requestCode, resultCode, data);
		}
	}

	private void showStatusMessage(int menuItem) {
		StringBuilder pIndexText = new StringBuilder();
		if (athlete != null) {
			switch (menuItem) {
				case R.id.athlete_stats_menu_runcount:
					pIndexText.append("Completed ").append(athlete.totalRuns()).append(" runs at ").append(athlete.eventCount()).append(" events.");
					break;
				case R.id.athlete_stats_menu_club:
					String club = athlete.clubStatus();
					if (club != null) {
						pIndexText.append("This athlete is in the ").append(club).append(" club.");
					}
					else {
						pIndexText.append("This athlete has not completed enough runs to join a parkrun club.");
					}
					break;
				case R.id.athlete_stats_menu_pindex:
					pIndexText.append("parkrun index = ").append(athlete.parkrunIndex()).append("\n");
					pIndexText.append("Improve after ").append(athlete.parkrunIndexImprovementEffort()).append(" runs.");
					break;
				case R.id.athlete_stats_menu_dataload:
					pIndexText.append("Data last loaded at ").append(athlete.dataLoadTime());
					break;
			}
		} else {
			pIndexText.append("No athlete has been loaded.");
		}
		Toast toast = Toast.makeText(getApplicationContext(), pIndexText.toString(), AppSettings.INFO_DISPLAY_TIME);
		toast.show();
	}


	protected void handleAthleteLoadResponse(int requestCode) {
		// We have received the news feed data load response.
		AthleteSummary athleteData = AthleteCache.getSingleton().getItem(String.valueOf(athleteId));

		// Update the athlete on the display
		if (athleteData != null) {
			updateAthlete(athleteData);
		} else {
			reportError("Could not retrieve requested athlete data.");
			finish();
		}
	}

	void updateAthlete(AthleteSummary athlete) {
		// Update the title
		if (athlete != null) {
			// Keep the athlete
			this.athlete = athlete;

			// Set the name in the title bar
			this.setTitle(athlete.getName());

			// Show the page content
			WebView browser = (WebView) findViewById(R.id.athlete_webview);
			browser.loadData(athlete.getPageContent(), "text/html", "UTF-8");
			
			// Has the data expired?
			if (athlete.hasDataExpired()) {
				StringBuilder expiryMessage = new StringBuilder();
				expiryMessage.append("Athlete data was last loaded at ");
				expiryMessage.append(athlete.dataLoadTime());
				expiryMessage.append(". It is possible that it is out of date. A data reload is recommended.");
				Toast toast = Toast.makeText(getApplicationContext(), expiryMessage.toString(), AppSettings.WARNING_DISPLAY_TIME);
				toast.show();
			}
			
		} else {
			this.setTitle("No athlete found.");
		}
	}

	public void showOnMap(View view) {
		loadEventData(IntentExtras.REQUEST_EVENT_DATA_LOAD_ALL_EVENTS);
	}

	@Override
	protected void handleEventLoadResponse(int requestCode) {
		Region world = ParkrunEventData.getSingleton().getWorld();
		switch (requestCode) {
		case IntentExtras.REQUEST_EVENT_DATA_LOAD_ALL_EVENTS:
			Log.d("PARKRUN", "Loaded event data, ready to show on map.");
			EventDisplay.startRegionDisplay(this, world, athleteId, -1);
			break;
		case IntentExtras.REQUEST_EVENT_DATA_COMPARE_ATHLETE_EVENTS:
			// Compare athletes on a map
			Log.d("PARKRUN", "Loaded event data, ready to compare athletes on map.");
			EventDisplay.startRegionDisplay(this, world, athleteId, compareAthleteId);			
			break;
		default:
			break;
		}
	}

	@Override
	protected void handleCountrySelectionResult(int requestCode, Intent data) {
		// Nothing required.
	}

	@Override
	protected void handleDataLoadError(int requestCode) {
		finish();
	}

	@Override
	protected void handleDataLoadCancel(int requestCode) {
		finish();
	}
}
